package com.sunshine.serialport.tools;


import org.apache.commons.lang3.StringEscapeUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @className:EncodeUtil.java
 * @classDescription:编码操作类
 * @author:xiayingjie
 * @createTime:2010-12-9
 */

public class EncodeUtil {

    private static final String DEFAULT_ENCODING = "UTF-8";// 设置默认编码为utf-8



    /**
     * URL 编码 默认设置为utf-8
     *
     * @param input
     * @return
     */
    public static String urlEncode(String input) {
        try {
            if (null == input || "".equals(input)) {
                return "";
            }
            return URLEncoder.encode(input, DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("urlEncode转换utf-8出错", e);
        }
    }

    /**
     * URL 解码, Encode默认为UTF-8
     *
     * @param input
     * @return
     */
    public static String urlDecode(String input) {
        try {
            return URLDecoder.decode(input, DEFAULT_ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("URLEncode解码出错", e);
        }
    }

    /**
     * Html 转码(将“<”转换成&lt;)
     *
     * @param html
     * @return
     */
    public static String htmlEscape(String html) {
        return StringEscapeUtils.escapeHtml4(html);

    }

    /**
     * Html 解码
     *
     * @param htmlEscaped
     * @return
     */
    public static String htmlUnescape(String htmlEscaped) {
        return StringEscapeUtils.unescapeHtml4(htmlEscaped);
    }

    /**
     * Xml 转码
     *
     * @param xml
     * @return
     */
    public static String xmlEscape(String xml) {
        return StringEscapeUtils.escapeXml(xml);
    }

    /**
     * Xml 解码
     *
     * @param xmlEscaped
     * @return
     */
    public static String xmlUnescape(String xmlEscaped) {
        return StringEscapeUtils.unescapeXml(xmlEscaped);
    }







}
